package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.configer.ConfigHelper;
import com.warrior.entity.TeamEntity;
import com.warrior.entity.UserEntity;
import com.warrior.entity.WxCache;
import com.warrior.service.TeamService;
import com.warrior.service.UserService;
import com.warrior.service.WxCacheService;
import com.warrior.util.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * team_controller
 * Created by Shawn on 2017/3/28.
 */
@Controller
@RequestMapping("/team")
public class TeamController {

    private static final Logger logger = LogManager.getLogger(TeamController.class.getName());

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserService userService;

    @Autowired
    private WxCacheService wxCacheService;

    @Autowired
    private HomeIntroductionController homeIntroductionController;

    /**
     * 获取队伍排名表
     *
     * @param page     当前页 取 1
     * @param size     页码大小 取20
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/ranking", method = RequestMethod.GET)
    public ModelAndView listTeamRanking(String page, String size, HttpServletRequest request, HttpServletResponse response) {
        if (logger.isDebugEnabled()) {
            logger.debug("listTeamRanking(String page={}, String size={}, HttpServletRequest request={}, HttpServletResponse response={}) - start", page, size, request, response); //$NON-NLS-1$
        }

        ModelAndView mv = new CModelAndView("/warrior/team/ranking_list", request, response);
        //取前20条数据,page 传 0 ,size 传 20
        Page<TeamEntity> teamEntities = this.teamService.findAllActiveTeam(CommonUtils.String2Int(page), CommonUtils.String2Int(size));
        mv.addObject("teamRanking", teamEntities);

        if (logger.isDebugEnabled()) {
            logger.debug("listTeamRanking(String, String, HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return mv;
    }

    /**
     * 根据队伍id获取队伍详情
     *
     * @param request  req
     * @param response resp
     * @param teamId   队伍id
     * @return ModelAndView
     */
    @RequestMapping(value = "/teamDetails", method = RequestMethod.GET)
    public ModelAndView findTeamById(HttpServletRequest request, HttpServletResponse response, String teamId) {
        ModelAndView mv = new CModelAndView("/warrior/team/team_details", request, response);
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        mv.addObject("teamInfo", teamEntity);
        List<UserEntity> userEntities = this.userService.findTeamMember(teamEntity.getCaptionId());
        //获取队伍成员
        mv.addObject("member", userEntities);
        return mv;
    }


    /**
     * 我的队伍
     *
     * @param request  req
     * @param response resp
     * @return ModelAndView
     */
    @RequestMapping(value = "/getMyTeam", method = RequestMethod.GET)
    public ModelAndView findMyTeam(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = null;
        WxChatAuthTools wxChatAuthTools = new WxChatAuthTools();
        String userId = (String) request.getSession().getAttribute("userId");
        UserEntity userEntity = this.userService.findUserById(userId);
        if (null != userEntity) {
            TeamEntity teamEntity = userEntity.getTeamEntity();
            if (null != teamEntity) {
                if (null == teamEntity.getTeamStatus()) {
                    mv = new CModelAndView("", request, response);
                } else {
                    mv = new CModelAndView("/warrior/team/my_team_1", request, response);
                    DateUtil dateUtil = new DateUtil();
                    mv.addObject("appId", ConfigHelper.getConfig().getString("WX.APP.ID"));// 必填，公众号的唯一标识
                    long timestamp = new Timestamp(new Date().getTime()).getTime()/1000;//截取到秒
                    mv.addObject("timestamp", timestamp); // 必填，生成签名的时间戳
                    logger.debug("timestamp:"+timestamp);
                    String nonceStr = "frYX2gezea9XTQ";
                    mv.addObject("nonceStr", nonceStr);//随机的字符串
                    //对签名进行加密
                    //拿到数据库中的token 和ticket
                    WxCache cache = this.wxCacheService.findCache();
                    String ticket = cache.getJsapiTicket();
                    logger.debug("ticket:"+ticket);
                    String url = request.getRequestURL().toString();
                    logger.debug("url:"+url);
                    //signature: 进行sha1 加密
                    String signature = wxChatAuthTools.generateSign(ticket, url, timestamp, nonceStr);
                    mv.addObject("signature", signature);
                    logger.debug("signature:"+signature);
                    mv.addObject("teamEntity", teamEntity);
                    //获取队员信息
                    List<UserEntity> userEntities = this.userService.findTeamMember(teamEntity.getCaptionId());
                    mv.addObject("teamMember", userEntities);
                    //添加队员时获取授权页面
                    String wxCodeUrl = wxChatAuthTools.getWxCode(1, teamEntity.getId());
                    mv.addObject("authorUrl", wxCodeUrl);
                    logger.debug("wxCodeUrl"+wxCodeUrl);
                }
            } else {
                mv = new CModelAndView("/warrior/team/team_create", request, response);
            }
        } else {
            mv = new CModelAndView("/500", request, response);
            mv.addObject("errorMsg","该用户不存在");
        }
        mv.addObject("userEntity", userEntity);
        return mv;
    }

    /**
     * 添加一个新的队伍
     *
     * @param request    req
     * @param response   res
     * @param leaderName 队长名
     * @param location   队伍位置
     * @param teamName   队伍名
     * @return ModelAndView
     */
    @RequestMapping(value = "/saveNewTeam", method = RequestMethod.POST)
    @ResponseBody
    public String startCreate(HttpServletRequest request, HttpServletResponse response, String leaderName, String location, String teamName,String mobile,String teamId) {
        DateUtil dateUtil = new DateUtil();
        TeamEntity teamEntity;
        if (null!=teamId){
           teamEntity = this.teamService.findTeamByTeamId(teamId);
           teamEntity.setTeamStatus(3);//设置为待审核队伍
        }else {
             teamEntity = new TeamEntity();
            teamEntity.setId("T-" + UUID.randomUUID().toString().replace("-", ""));
            teamEntity.setCreatedBy("admin");
            teamEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
            teamEntity.setTeamStatus(0);//设置为未激活待审核队伍
            teamEntity.setTeamIntegral(0);//初始积分
            teamEntity.setDrawNum(0);//设置初始胜负场
            teamEntity.setWinNum(0);
            teamEntity.setLoseNum(0);

        }
        teamEntity.setUpdateBy("admin");
        teamEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));

        teamEntity.setIsLocked(0);//第一次未上锁
        //设置当前用户为队长
        String userId = (String) request.getSession().getAttribute("userId");
        teamEntity.setCaptionId(userId);
        teamEntity.setLeaderName(leaderName);
        teamEntity.setLocation(location);
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        logger.debug("filePathName:" + saveFilePathName);
        Map map;
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    teamEntity.setLogoPath(savePath);//上传队标图片的path
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        teamEntity.setName(teamName);
        teamEntity.setLeaderMobile(mobile);
        this.teamService.saveNewTeamWithMobile(teamEntity,mobile);
        String returnMap = null;
        try {
             returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 解散或删除队员
     *
     * @param request request
     * @param teamId  队伍id
     * @return String
     * @throws ProjectException 出现异常
     */
    @RequestMapping("/dismissTeam")
    @ResponseBody
    public String dismissTeam(HttpServletRequest request, String teamId, String userId) throws ProjectException {
        try {
            this.teamService.dismissTeamByUser(userId, teamId);
            return ServerResponse.okToJsonString("success");

        } catch (ProjectException | JsonProcessingException e) {
            e.printStackTrace();
            throw new ProjectException(e.getMessage());
        }
    }


    /**
     * 微信邀请
     *
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping("/invite_teammate")
    public ModelAndView inviteTeammate(HttpServletRequest request, HttpServletResponse response, String code, String state) throws IOException {
        ModelAndView mv = new CModelAndView("/warrior/team/team_join", request, response);
        String teamId = state;
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        mv.addObject("teamEntity",teamEntity);
        List<UserEntity> teamMember = this.userService.findTeamMember(teamEntity.getCaptionId());
        mv.addObject("teamMember",teamMember);
        //添加用户信息
        homeIntroductionController.userLogin(request, code);
        return mv;
    }


    @RequestMapping("/create_team_step1")
    public ModelAndView createTeamStep1(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/team/create_team", request, response);
        return mv;
    }

    @RequestMapping("/create_team_complete")
    public ModelAndView createTeamComplete(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/team/create_complete", request, response);
        return mv;
    }


    /**
     * 修改队伍锁定状态
     *
     * @param teamId 队伍id
     * @param status 修改后的状态
     * @return String Json
     */
    @RequestMapping(value = "modify_status", method = RequestMethod.POST)
    @ResponseBody
    public String modifyStatus(String teamId, String status) {
        String returnMap = null;
        try {
            this.teamService.switchLockedStatus(teamId, CommonUtils.String2Int(status));
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 接受邀请
     *
     * @param request       request
     * @param response      response
     * @param invitedUserId 邀请人id
     * @param teamId        队伍id
     * @return ModelAndView
     */
    @RequestMapping("/accept_invite")
    @ResponseBody
    public String acceptInvited(HttpServletRequest request, HttpServletResponse response, String invitedUserId, String teamId) throws JsonProcessingException {
        String userId = (String) request.getSession().getAttribute("userId");
        String returnMap;
        UserEntity user = this.userService.findUserById(userId);
        if(null != user) {
            if (null == user.getTeamEntity()) {
                TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
                List<UserEntity> teamMember = this.userService.findTeamMember(invitedUserId);
                if (teamMember.size() < CommonUtils.String2Int(ConfigHelper.getConfig().getString("team.limit"))) {
                    user.setTeamEntity(teamEntity);
                    this.userService.saveUser(user);
                    returnMap = ServerResponse.okToJsonString("success");
                } else {
                    returnMap = ServerResponse.okToJsonString("队伍已满员");
                }
            } else {
                returnMap = ServerResponse.okToJsonString("你已经参加其他队伍");
            }
        }else{
            returnMap =ServerResponse.okToJsonString("未找到该用户");
        }
        return returnMap;
    }

    /**
     * 成功跳转回调页面
     *
     * @param request request
     * @param response response
     * @param teamId 队伍id
     * @param invitedUserId 邀请人id
     * @return
     */
    @RequestMapping(value = "/accept_success", method = RequestMethod.GET)
    public ModelAndView acceptSuccess(HttpServletRequest request, HttpServletResponse response, String teamId, String invitedUserId) {
        ModelAndView mv = new CModelAndView("/warrior/team/join_success", request, response);
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        mv.addObject("teamEntity", teamEntity);
        UserEntity userEntity = this.userService.findUserById(invitedUserId);
        mv.addObject("invitedUser", userEntity);
        return mv;
    }

    @RequestMapping("apply_for_career1")
    public ModelAndView applyForCareer(HttpServletRequest request,HttpServletResponse response,String teamId){
        ModelAndView mv = new CModelAndView("/warrior/team/turn_professional",request,response);
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        mv.addObject("team",teamEntity);
        //获取队员信息
        List<UserEntity> userEntities = this.userService.findTeamMember(teamEntity.getCaptionId());
        mv.addObject("teamMember", userEntities);
        return mv;
    }

    /**
     *
     * @param request req
     * @param response resp
     * @param captionId 队长id
     * @param teamName 队伍名
     * @param captionName 队长名
     * @param mobile 手机
     * @param area 地区
     * @param teamId 队伍id
     * @return
     */
    @RequestMapping("apply_for_career2")
    public ModelAndView applyForCareer2(HttpServletRequest request,HttpServletResponse response,String captionId,String teamName,String captionName,String mobile,String area,String teamId){
        ModelAndView mv = new CModelAndView("/warrior/team/turn_professional2",request,response);
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        teamEntity.setName(teamName);
        teamEntity.setLeaderName(captionName);
        teamEntity.setLeaderMobile(mobile);
        teamEntity.setLocation(area);
        this.teamService.saveNewTeam(teamEntity);
        List<UserEntity> teamMember = this.userService.findTeamMember(captionId);
        mv.addObject("teamMember",teamMember);
        return mv;
    }

    @RequestMapping("apply_for_career3")
    public ModelAndView applyForCareer3(HttpServletRequest request,HttpServletResponse response,String teamId,String captionId){
        ModelAndView mv = new CModelAndView("/warrior/team/turn_professional3",request,response);
        List<UserEntity> teamMember = this.userService.findTeamMember(captionId);
        if(teamMember.size()==7){
            TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
            teamEntity.setTeamStatus(3);
            this.teamService.saveNewTeam(teamEntity);
        }else {
            mv.addObject("error","不符合转职业队条件");
        }
        return mv;
    }



    @RequestMapping(value = "/upload_user_idCard",method = RequestMethod.POST)
    @ResponseBody
    public String uploadUserIdCard(HttpServletRequest request,String userId){
        UserEntity userEntity = this.userService.findUserById(userId);
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        logger.debug("filePathName:" + saveFilePathName);
        Map map;
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    userEntity.setIdCardPicPath(savePath);//上传身份证的path
                    this.userService.saveUser(userEntity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    @RequestMapping(value = "validate_mobile",method = RequestMethod.POST)
    @ResponseBody
    public String validateMobile(String mobile){
        TeamEntity teamEntity = this.teamService.findTeamByMobile(mobile);
        String returnMap = null;
        try {
        if (null == teamEntity){
            returnMap = ServerResponse.okToJsonString("success");
        }else {
            returnMap = ServerResponse.okToJsonString("队长手机号重复");
        }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    @RequestMapping(value = "validate_teamName",method = RequestMethod.POST)
    @ResponseBody
    public String validateTeamName(String teamName){
        TeamEntity teamEntity = this.teamService.findTeamByTeamName(teamName);
        String returnMap = null;
        try {
            if (null == teamEntity){
                returnMap = ServerResponse.okToJsonString("success");
            }else {
                returnMap = ServerResponse.okToJsonString("队伍名重复");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value = "/teamTransform",method = RequestMethod.GET)
    public ModelAndView teamTransform(HttpServletRequest request,HttpServletResponse response,String teamId){
        WxChatAuthTools wxChatAuthTools = new WxChatAuthTools();
        ModelAndView mv = new CModelAndView("warrior/team/team_transform",request,response);
        String wxCodeUrl = wxChatAuthTools.getWxCode(1, teamId);
        mv.addObject("authorUrl", wxCodeUrl);
        logger.debug("wxCodeUrl"+wxCodeUrl);
        return mv;
    }


    /**
     * 修改用户头像
     *
     * @param request  request
     * @param response response
     * @return String
     */
    @RequestMapping(value = "/uploadTeamLogo", method = RequestMethod.POST)
    @ResponseBody
    public String uploadPic(HttpServletRequest request, HttpServletResponse response,String teamId) {
        String returnMsg = null;
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        logger.debug("filePathName:" + saveFilePathName);
        Map map;
        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    teamEntity.setLogoPath(savePath);
                    this.teamService.saveNewTeam(teamEntity);
                    returnMsg = ServerResponse.okToJsonString("success");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnMsg;
    }


}
